var curScriptExecution = null;
var mobile = '';
var showIndex = 0;
function getConfig () {
  try {
    var url = 'http://47.120.74.135/api/exec/get';
    var res = http.get (url);
    var data = res.body.string ();
    return JSON.parse (data);
  } catch (e) {
    console.log (e);
    return null;
  }
}

function afterScript () {
  showIndex = 0;
  try {
    var url = 'http://47.120.74.135/api/exec/fingerPrint?fingerPrint=' + mobile;
    http.get (url);
  } catch (e) {
    console.show ();
    console.log ('afterScript Error:', e);
    sleep (2 * 1000);
    console.hide ();
    return;
  }
}

function loadCode (config) {
  var server = config.server;
  var port = config.port;
  var projectName = config.projectName;
  var path = config.path;
  try {
    var res = http.get (
      'http://' + server + ':' + port + '/' + projectName + '/' + path
    );
    var code = res.body.string ();
    return code;
  } catch (e) {
    console.log (e);
    return null;
  }
}
function getParams (params) {
  if (!params) {
    return '';
  }
  return params
    .split (',')
    .map (item => {
      return '"' + item + '"';
    })
    .join (',');
}
function execScript (config) {
  var execTimes = config.execTimes || 1;
  var params = config.params || '';
  var fingerPrint = config.fingerPrint || '';
  if (fingerPrint && fingerPrint.split (',').indexOf (mobile) > -1) {
    if (showIndex == 0) {
      console.show ();
      console.log ('代码在设备' + mobile + '已经运行过了');
      sleep (2 * 1000);
      console.hide ();
      showIndex++;
    }
    sleep (10 * 1000);
    return;
  }
  var code = loadCode (config);
  if (!code) {
    console.show ();
    console.log ('下载代码失败');
    sleep (2 * 1000);
    console.hide ();
    sleep (15 * 1000);
    return;
  }
  curScriptExecution = engines.execScript (
    'execScript',
    'for (var index = 0; index < ' +
      execTimes +
      '; index++) {var Wang = {};' +
      code +
      ';Wang.main(' +
      getParams (params) +
      ')' +
      '};'
  );
  afterScript ();
}

function main () {
  while (true) {
    if (
      curScriptExecution &&
      curScriptExecution.getEngine () &&
      !curScriptExecution.getEngine ().isDestroyed ()
    ) {
      console.log ('开始 sleep');
      sleep (20 * 1000);
    } else {
      console.log ('开始 getConfig');
      var config = getConfig ();
      if (!config) {
        console.show ();
        console.log ('获取配置失败');
        sleep (2 * 1000);
        console.hide ();
        sleep (10 * 1000);
      } else {
        execScript (config.data);
      }
    }
  }
}

main ();
